import { defineStore } from 'pinia'
import { ref, reactive, computed } from 'vue'
// 新增：后端登录接口
import { login as loginApi } from '@/api/loginApi.js'

// Simple UUID generator for device id
function uuid(){
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    const r = Math.random()*16|0, v = c==='x' ? r : (r&0x3|0x8)
    return v.toString(16)
  })
}

function now(){ return new Date().toISOString() }

const STORAGE_KEY = 'auth_state'

export const useAuthStore = defineStore('auth', () => {
  const user = ref(null) // { id, name, phone, provider? }
  const token = ref('')
  const addresses = ref([]) // [{id,name,phone,address}]
  const cards = ref([]) // [{id,bank,cardNoMasked,last4}]
  const bindings = reactive({ alipay: false, wechat: false })
  const paymentPasswordSet = ref(false)
  const faceVerified = ref(false)
  const loginLogs = ref([]) // [{time, method, deviceId}]
  const devices = ref([]) // [{id, name, trusted, lastLogin}]
  const abnormalAlerts = ref([])
  const alertSwitch = ref(true)

  // device id from localStorage
  const currentDeviceId = ref(localStorage.getItem('deviceId') || (()=>{
    const id = uuid(); localStorage.setItem('deviceId', id); return id
  })())
  const currentDeviceName = ref(navigator.userAgent?.slice(0,60) || 'Unknown Device')

  const isLoggedIn = computed(() => !!token.value && !!user.value)

  function persist(){
    const state = {
      user: user.value, token: token.value, addresses: addresses.value,
      cards: cards.value, bindings: { ...bindings }, paymentPasswordSet: paymentPasswordSet.value, faceVerified: faceVerified.value,
      loginLogs: loginLogs.value, devices: devices.value, abnormalAlerts: abnormalAlerts.value,
      alertSwitch: alertSwitch.value
    }
    localStorage.setItem(STORAGE_KEY, JSON.stringify(state))
  }

  function restore(){
    try{
      const raw = JSON.parse(localStorage.getItem(STORAGE_KEY) || 'null')
      if(raw){
        user.value = raw.user
        token.value = raw.token
        addresses.value = raw.addresses || []
        cards.value = raw.cards || []
        bindings.alipay = !!raw.bindings?.alipay
        bindings.wechat = !!raw.bindings?.wechat
        paymentPasswordSet.value = !!raw.paymentPasswordSet
        faceVerified.value = !!raw.faceVerified
        loginLogs.value = raw.loginLogs || []
        devices.value = raw.devices || []
        abnormalAlerts.value = raw.abnormalAlerts || []
        alertSwitch.value = raw.alertSwitch !== false
      }
    }catch{}
  }

  function addLog(method){
    loginLogs.value.unshift({ time: now(), method, deviceId: currentDeviceId.value })
    const d = devices.value.find(d => d.id === currentDeviceId.value)
    if(d){ d.lastLogin = now() }
    else {
      devices.value.unshift({ id: currentDeviceId.value, name: currentDeviceName.value, trusted: false, lastLogin: now() })
    }
    detectAbnormal()
    persist()
  }

  function detectAbnormal(){
    // Simple heuristic: more than 2 new devices in 24h
    const map = new Map()
    const last24h = Date.now() - 24*3600*1000
    let count = 0
    for(const log of loginLogs.value){
      const t = new Date(log.time).getTime()
      if(t >= last24h){
        if(!map.has(log.deviceId)){ map.set(log.deviceId, true); count++ }
      } else break
    }
    if(count >= 3 && alertSwitch.value){
      abnormalAlerts.value.unshift({ time: now(), type: 'multi-device', message: '24小时内多设备登录，请确认是否为本人操作。' })
    }
  }

  // 新增：对接后端的账号密码登录
  async function login({ account, password }){
    if(!account || !password) throw new Error('请输入账号与密码')
    const resp = await loginApi({ account, username: account, password })
    const { code, data, msg } = resp?.data || {}
    if (code !== 200) throw new Error(msg || '登录失败')

    const tokenVal = data?.token || ''
    token.value = tokenVal
    // 交给 axios 请求拦截器从 sessionStorage 注入到请求头
    sessionStorage.setItem('token', tokenVal)

    user.value = {
      id: data?.userId ?? data?.id ?? '',
      name: data?.nickName || data?.username || '',
      phone: data?.mobile || ''
    }

    addLog('password')
    persist()
  }

  function loginWithPassword(account, password){
    // Demo: accept non-empty and password length >=6; real app via backend
    if(!account || !password) throw new Error('请输入账号与密码')
    if(String(password).length < 6) throw new Error('密码至少6位')
    const profile = { id: account, name: '用户'+String(account).slice(-4), phone: /\d{11}/.test(account) ? account : '' }
    user.value = profile
    token.value = 'token_'+uuid()
    addLog('password')
  }

  function loginWithSMS(phone, code){
    if(!/^\d{11}$/.test(phone)) throw new Error('手机号格式不正确')
    const saved = localStorage.getItem('sms_'+phone)
    const exp = Number(localStorage.getItem('sms_exp_'+phone) || 0)
    if(!saved) throw new Error('请先获取验证码')
    if(Date.now() > exp) throw new Error('验证码已过期，请重新获取')
    if(code !== saved) throw new Error('验证码错误')
    user.value = { id: phone, name: '用户'+phone.slice(-4), phone }
    token.value = 'token_'+uuid()
    addLog('sms')
    localStorage.removeItem('sms_'+phone)
    localStorage.removeItem('sms_exp_'+phone)
  }

  function thirdPartyLogin(provider){
    user.value = { id: provider+'_'+uuid().slice(0,8), name: provider==='wechat'?'微信用户':'支付宝用户', phone: '' }
    token.value = 'token_'+uuid()
    addLog(provider)
  }

  function logout(){
    user.value = null
    token.value = ''
    sessionStorage.removeItem('token')
    persist()
  }

  function sendSMS(phone){
    if(!/^\d{11}$/.test(phone)) throw new Error('手机号格式不正确')
    const lastKey = 'sms_last_'+phone
    const expKey = 'sms_exp_'+phone
    const codeKey = 'sms_'+phone
    const last = Number(localStorage.getItem(lastKey) || 0)
    const nowTs = Date.now()
    if(nowTs - last < 60_000){
      const remain = Math.ceil((60_000 - (nowTs - last))/1000)
      throw new Error(`发送过于频繁，请${remain}s后再试`)
    }
    const code = String(Math.floor(100000 + Math.random()*900000))
    localStorage.setItem(codeKey, code)
    localStorage.setItem(expKey, String(nowTs + 5*60_000)) // 5分钟有效
    localStorage.setItem(lastKey, String(nowTs))
    // Real app will call SMS gateway; code not exposed
    return code
  }

  function setPaymentPassword(pin){
    if(!/^\d{6}$/.test(pin)) throw new Error('支付密码需为6位数字')
    localStorage.setItem('pay_pin_hash', btoa(pin))
    paymentPasswordSet.value = true
    persist()
  }
  function changePassword(oldPwd, newPwd){
    if(!isLoggedIn.value) throw new Error('未登录')
    if(!newPwd || newPwd.length < 6) throw new Error('新密码至少6位')
    // For demo, accept any
    addLog('change-password')
  }
  function forgotPassword(phone, code, newPwd){
    if(!/^\d{11}$/.test(phone)) throw new Error('手机号格式不正确')
    const saved = localStorage.getItem('sms_'+phone)
    const exp = Number(localStorage.getItem('sms_exp_'+phone) || 0)
    if(!saved) throw new Error('请先获取验证码')
    if(Date.now() > exp) throw new Error('验证码已过期，请重新获取')
    if(code !== saved) throw new Error('验证码错误')
    if(!newPwd || newPwd.length < 6) throw new Error('新密码至少6位')
    // Accept
    localStorage.removeItem('sms_'+phone)
    localStorage.removeItem('sms_exp_'+phone)
  }

  // Address
  function addAddress(item){ item.id = uuid(); addresses.value.unshift(item); persist() }
  function updateAddress(id, patch){ const a = addresses.value.find(x=>x.id===id); if(a) Object.assign(a, patch); persist() }
  function removeAddress(id){ addresses.value = addresses.value.filter(x=>x.id!==id); persist() }

  // Card
  function addCard({ bank, cardNo }){
    if(!/^[0-9]{12,19}$/.test(cardNo)) throw new Error('卡号格式不正确')
    const last4 = cardNo.slice(-4)
    cards.value.unshift({ id: uuid(), bank, cardNoMasked: cardNo.replace(/\d(?=\d{4})/g,'*'), last4 })
    persist()
  }
  function removeCard(id){ cards.value = cards.value.filter(x=>x.id!==id); persist() }

  // Bindings
  function bindAlipay(flag){ bindings.alipay = !!flag; persist() }
  function bindWechat(flag){ bindings.wechat = !!flag; persist() }

  // Face verification (simulated)
  function verifyFace(){ faceVerified.value = true; addLog('face-verify'); persist() }

  // Devices
  function trustDevice(id, trusted){ const d = devices.value.find(x=>x.id===id); if(d){ d.trusted = !!trusted; persist() } }
  function removeDevice(id){ devices.value = devices.value.filter(x=>x.id!==id); persist() }

  restore()
  return {
    user, token, isLoggedIn, addresses, cards, bindings, paymentPasswordSet, faceVerified, loginLogs, devices, abnormalAlerts, alertSwitch,
    currentDeviceId, currentDeviceName,
    // 导出后端登录方法
    login,
    loginWithPassword, loginWithSMS, thirdPartyLogin, logout, sendSMS,
    setPaymentPassword, changePassword, forgotPassword, verifyFace,
    addAddress, updateAddress, removeAddress,
    addCard, removeCard,
    bindAlipay, bindWechat,
    trustDevice, removeDevice,
    persist
  }
})